package com.igoal.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.igoal.common.SessionConstants;
import com.igoal.dto.UserDTO;
import com.igoal.service.MailServiceImpl;
import com.igoal.service.MessageManager;
import com.igoal.service.SaveResult;
import com.igoal.service.UserManagerExt;
import com.igoal.utils.RandomString;
import com.igoal.web.model.BaseModel;

@Controller
@RequestMapping("/forgotPassword.html")
public class ForgotPasswordController extends BaseController {
	private Log logger = LogFactory.getLog(ForgotPasswordController.class);
	private MailServiceImpl mailService;
	
	public String getViewPrefix() {
		return BaseControllerDelegate.DEFAULT_VIEW_PREFIX;
	}

	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}

	@Autowired
	public void setMailService(MailServiceImpl mailService) {
		this.mailService = mailService;
	}

	@Autowired
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String execute(HttpServletRequest request) {
		if (isLoginUser()) {
			return getViewPrefix() + "userDashboard";
		}
		request.getSession().removeAttribute(Captcha.NAME);
		return getViewPrefix() + "forgotPassword";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String sendPassword(@RequestParam("action") String action,
			@RequestParam("login") String login,
			@RequestParam("check") String securityCode,
			HttpServletRequest request) {

		if (SessionConstants.FORGOT_PASS_SEND_ACTION.equals(action)) {
			boolean success = true;
			HttpSession session = request.getSession();
			request.setAttribute(SessionConstants.FORGOT_PASS_LOGIN_NAME, login);

			Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
			if (captcha.isCorrect(securityCode)) {
				UserDTO user = null;
				try {
					user = userManagerExt.getUserByUsername(login);
				} catch (Exception e) {
					logger.debug("User login not found");
				}

				if (user == null) {
					request.setAttribute(
							SessionConstants.FORGOT_PASS_LOGIN_NAME_ERROR, true);
					success = false;
				} else {
					String newPassword = RandomString.generate(10);
					int result = userManagerExt.savePassword(user, newPassword);
					if (result == SaveResult.SUCCESS) {
						mailService.sendPassword(user, newPassword);
						logger.debug("Create new password for "
								+ user.getUsername() + " successfully");
					} else {
						success = false;
						logger.debug("Create new password for "
								+ user.getUsername() + " unsuccessfully");
					}
				}
			} else {
				request.setAttribute(
						SessionConstants.FORGOT_PASS_SECURITY_CODE_ERROR, true);
				success = false;
			}

			// remove captcha image
			session.removeAttribute(Captcha.NAME);

			if (success) {
				request.setAttribute(SessionConstants.FORGOT_PASS_SUCCESS, true);
			}
		}

		return getViewPrefix() + "forgotPassword";
	}

	public void initTopPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

	public void initRightPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

	public void initLeftPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

}
